//
// Created by ChenJi on 2020/12/4.
//

#include "rader.h"
#include "usart_extern.h"
#include "string_library.h"
extern UART_HandleTypeDef huart4;
extern UART_HandleTypeDef huart1;
extern DMA_HandleTypeDef hdma_uart4_rx;
extern uint8_t uart4_buffer[];
uint16_t distance = 0;
uint16_t single = 0;
uint8_t exist = 0;

uint8_t is_Radar_Initing = 1;
uint8_t Found0x55 = 0;
uint8_t count = 0;

void init_rader() {
    rader_power_on();

}

void onUART4Receive(uint8_t data) {
    if (is_Radar_Initing) {
        if (data == 0x55) {
            Found0x55 = 1;
        }
        if (Found0x55) {
            count++;
        }
        if (count == 14) {
            is_Radar_Initing = 0;
            count = 0;
            Found0x55 = 0;
            HAL_DMA_Abort(&hdma_uart4_rx);
            HAL_UART_Receive_DMA(&huart4, uart4_buffer, 13);
            debug("Radar init done\n");
        }
        return;
    }



   //  sendData_DMA(uart4_buffer, &huart1, 13);
    if (uart4_buffer[0] != 0x55) {
        debug("[Radar] Bad Pocket Drop\n");
        is_Radar_Initing = 1;
        HAL_DMA_Abort(&hdma_uart4_rx);
        HAL_UART_Receive_DMA(&huart4, uart4_buffer, 1);
        return;
    }
   // debug_sync("[Radar] Distance：");
 //   uint8_t buf[10];
    uint16_t d1 = uart4_buffer[4] << 8 | uart4_buffer[5];
 //   myitoa(d1,buf,10);debug_sync(buf); debug_sync(" Signal: ");
    uint16_t s1 = uart4_buffer[8] << 8 | uart4_buffer[9];
 //   myitoa(s1,buf,10);debug_sync(buf);
 ////   debug_sync("\n");
    uint8_t e1 = uart4_buffer[7];
    if (exist != e1) {
        onRaderSwapState(e1);
        if (e1)
            onRederFind(d1, s1);
        else
            onRaderLeave(d1, s1);
    }
    if (d1 != distance || s1 != distance)
        onRederUpdate(d1, s1);
    distance = d1;
    single = s1;
    exist = e1;
}

__weak void onRederUpdate(uint16_t distance, uint16_t single) {

}

__weak void onRederFind(uint16_t distance, uint16_t single) {
    debug("[Radar]Radar_Find\n");
}

__weak void onRaderLeave(uint16_t distance, uint16_t single) {
    debug("[Radar]Radar_Leave\n");
}

__weak void onRaderSwapState(uint8_t state) {
 //   debug("[Radar]Radar_Swap_State\n");
}

uint16_t fetch_current_distance() {
    return distance;
}

uint16_t fetch_current_single() {
    return single;
}

uint8_t fetch_state() {
    return exist;
}

void rader_power_on() {
    debug_UART1("Rader power on\n", 15);
}

void rader_power_off() {
    debug_UART1("Rader power off\n", 16);
}